package it.fuesi.expired.api.client;

import it.fuesi.expired.api.AttachmentService;
import it.fuesi.expired.api.client.base.AClientBroker;
import it.fuesi.expired.model.Attachment;
import it.fuesi.expired.model.base.ErrorModel;

import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

public class AttachmentsBroker extends AClientBroker implements AttachmentService{

	public AttachmentsBroker(String endpoint) {
		super(endpoint);
	}
	
	@Override
	protected String getResourceUri() {
		return AttachmentService.BASE_URI;
	}

	public byte[] getFile(String _id){
		final String url = getEndpoint() + getResourceUri() + "/" + _id;
		
		final RestTemplate restTemplate = getBasicByteArrayRestTemplate();
		
		return restTemplate.getForObject(url, byte[].class);
		
	}
	
	public Attachment putFile(final Attachment att, byte[] data){
		
		MultiValueMap<String, Object> parts = new LinkedMultiValueMap<String, Object>();

		ByteArrayResource contentsAsResource = new ByteArrayResource(data){
            @Override
            public String getFilename(){
                return att.getFileName();
            }
        };
		
		parts.add("data", contentsAsResource);
		
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        
        
		HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity<MultiValueMap<String,Object>>(parts,headers);
		ResponseEntity<Attachment> response = execute(getResourceUri(), HttpMethod.POST, request, Attachment.class);
		
		
		
		return response.getBody();
	}
	
	public ErrorModel cleanFiles(){
		final ResponseEntity<ErrorModel> response = execute(getResourceUri() + "/clean", HttpMethod.DELETE, null, ErrorModel.class);
		return response != null ? response.getBody() : null;
	}
	

}
